package com.qc.serviceedu.entity.Excel.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qc.servicebase.config.GuliException;
import com.qc.serviceedu.entity.Excel.SubjectData;
import com.qc.serviceedu.entity.EduSubject;
import com.qc.serviceedu.service.EduSubjectService;


public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    //不能实现数据库操作
    public EduSubjectService subjectService;

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    public SubjectExcelListener() {

    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new GuliException(20001,"文件数据为空");
        }
        //一行一行读取，每次都有两个值，第一个值是一级分类，第二个值是二级分类
        //判断一级分类是否重复
        EduSubject OneSubject = this.existOneSubject(subjectService,subjectData.getOneSubjectName());
        if (null == OneSubject){  //没有相同的一级分类，添加
            OneSubject = new EduSubject();
            OneSubject.setParentId("0");
            OneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(OneSubject);
        }
        //判断二级分类是否重复
        String pid =OneSubject.getId() ;
        EduSubject TwoSubject = this.existTwoSubject(subjectService,subjectData.getOneSubjectName(),pid);
        if (null == TwoSubject){  //没有相同的一级分类，添加
            TwoSubject = new EduSubject();
            TwoSubject.setParentId(pid);
            TwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(TwoSubject);
        }
    }

    //判断一级分类不能重复
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",0);
        EduSubject OneSubject = subjectService.getOne(queryWrapper);
        return OneSubject;
    }

    //判断二级分类不能重复
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        EduSubject twoSubject = subjectService.getOne(queryWrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
